import util from '@/libs/util';
import Cookies from 'js-cookie';

export default {
    name: 'exportable-table',
    data () {
        return {
            columns: [{
                title: '订单号',
                key: 'billcode'
            }, {
                title: '学生姓名',
                key: 'student_name'

            }, {
                title: '班级名称',
                key: 'class_name'

            }, {
                title: '支付总金额',
                key: 'amt'

            }, {
                title: '应收金额',
                key: 'real_amt'

            }, {
                title: '打折金额',
                key: 'discount_amt'

            }, {
                title: '创建时间',
                key: 'createtime',
                render: (h, params) => {
                    return h('span', {}, util.getDate(params.row.createtime, 'time'));
                }

            }, {
                title: '支付截至时间',
                key: 'chargevalidity',
                render: (h, params) => {
                    return h('span', {}, util.getDate(params.row.chargevalidity, 'time'));
                }

            }, {
                title: '订单状态',
                key: 'status',
                render: (h, params) => {
                    let text = '';
                    if (params.row.status === 1) text = '待缴费';
                    if (params.row.status === 2) text = '已缴费';
                    if (params.row.status === 3) text = '申请退款';
                    if (params.row.status === 4) text = '已退款';
                    if (params.row.status === 5) text = '已失效';
                    return h('span', {}, text);
                }
            }, {
                title: '操作',
                render: (h, params) => {
                    if (params.row.status == 1) {
                        return h('Button', {
                            props: {
                                type: 'primary',
                                size: 'small'
                            },
                            style: {
                                marginRight: '5px'
                            },
                            on: {
                                click: () => {
                                    this.billId = params.row.id;
                                    this.chargeDetailVisable = true;
                                    this.getOrderDetails();
                                    util.ajax.post('/base/datadictionary/findByCode', util.toFormData(
                                        {CODE: 'PAY_TYPE'}
                                    )).then(res => { // 获得区域数据
                                        if (res.data.code == 200) {
                                            var data = res.data.data;
                                            this.payTypeList = data;
                                        }
                                    });
                                }
                            }
                        }, '缴费');
                    }
                }
            }],
            total: 0,
            pageSize: 10,
            pageIndex: 1,
            dataList: [],
            classSeasonList: [],
            areaList: [],
            billId: '',
            baseuser: JSON.parse(Cookies.get('baseUser')),
            queryData: {
                billCode: '',
                studentName: '',
                parentPhone: '',
                className: '',
                status: '',
                areaId: '',
                classYear: '',
                classSeason: ''
            },
            chargeDetailVisable: false,
            chargeDiscountVisable: false,
            charge_columns_1: [
                {
                    title: '项目名称',
                    key: 'name'
                }, {
                    title: '金额(元)',
                    key: 'amt'
                }, {
                    title: '打折金额',
                    key: 'discountedAmt'
                }, {
                    title: '打折理由'
                }],
            charge_columns_2: [
                {
                    title: '项目名称',
                    key: 'name'
                }, {
                    title: '金额(元)',
                    key: 'amt'
                }, {
                    title: '应收金额',
                    key: 'realAmt'
                }, {
                    title: '已打折金额',
                    key: 'discountedAmt'
                }, {
                    title: '减免金额',
                    key: 'discountAmt',
                    render: (h, params) => {
                        return h('Input', {
                            props: {
                                value: params.row.discountAmt
                            },
                            on: {
                                'on-blur': (event) => {
                                    let index = params.index;
                                    this.charge_dataList[index].discountAmt = event.target.value;
                                }
                            }
                        });
                    }
                },
                {
                    title: '操作',
                    key: 'opt',
                    render: (h, params) => {
                        let list = [];
                        let discountAmt = params.row.discountedAmt;
                        if(discountAmt>0){
                            list.push(
                                h('Button',{
                                    props: {
                                        type: 'primary',
                                        size: 'small'
                                    },
                                    style: {
                                        marginRight: '5px'
                                    },
                                    on: {
                                        click: () => {

                                            this.$Modal.confirm({
                                                content: '确定取消此项打折?',
                                                onOk: () => {
                                                    this.cancelDiscount(params.row.id);
                                                },
                                                onCancel: () => {

                                                }
                                            });
                                        }
                                    }
                                },'取消打折')
                            );
                        }
                        if (params.row.chargeType == 2) {
                            list.push( h('Button', {
                                props: {
                                    type: 'error',
                                    size: 'small'
                                },
                                style: {
                                    marginRight: '5px'
                                },
                                on: {
                                    click: () => {
                                        this.$Modal.confirm({
                                            content: '确定删除收费项?',
                                            onOk: () => {
                                                util.ajax.post('/busine/charge/delete', util.toFormData({
                                                    id: params.row.id
                                                })).then(res => {
                                                    if (res.data.code == 200) {
                                                        this.$Message.success('删除成功');
                                                        this.getOrderDetails();
                                                    } else {
                                                        this.$Message.error(res.data.message);
                                                    }
                                                });
                                            },
                                            onCancel: () => {
                                            }
                                        });
                                    }
                                }
                            }, '删除'));
                        }
                        return h('span',list);
                    }
                }],
            class_columns: [
                {
                    title: '班级名称',
                    key: 'class_name'
                }, {
                    title: '班级代码',
                    key: 'class_code'
                }, {
                    title: '学年',
                    key: 'class_year'
                }, {
                    title: '学期',
                    key: 'class_season_name'
                }, {
                    title: '专业',
                    key: 'marjor_name'
                }, {
                    title: '负责教师',
                    key: 'teacher_name'
                }, {
                    title: '课程安排',
                    key: 'classSchedules'
                }, {
                    title: '录取方'
                }, {
                    title: '总费用',
                    key: 'amt'
                }],
            class_dataList: [],
            charge_dataList: [],
            orderDetails: {},
            discountRate: '',
            payType: '',
            discountTypeList: [],
            payNumVisible: false,
            payNum: '',
            modalLoading: false,
            payTypeList:[]
        };
    },
    mounted () {
        this.init();
        this.loadList();
    },
    methods: {
        whenSelectDiscountType: function (event) {
            this.discountRate = event.value;
            this.countDiscount();
        },
        getDiscountType: function () {
            util.ajax.post('/base/discount/type/list', util.toFormData({})).then(res => {
                this.discountTypeList = res.data.data.list;
            });
        },
        init: function () {
            util.ajax.post('/base/datadictionary/findByCode', util.toFormData(
                {CODE: 'CLASS_SEASON'}
            )).then(res => { // 学期数据
                if (res.data.code == 200) {
                    var data = res.data.data;
                    this.classSeasonList = data;
                }
            });
            util.ajax.post('/base/datadictionary/findByCode', util.toFormData(
                {CODE: 'AREA_TYPE'}
            )).then(res => { // 获得区域数据
                if (res.data.code == 200) {
                    var data = res.data.data;
                    this.areaList = data;
                }
            });
        },
        loadList: function () {
            util.ajax.post('/busine/charge/listBySql', util.toFormData({
                page: this.pageIndex,
                size: this.pageSize,
                billCode: this.queryData.billCode,
                studentName: this.queryData.studentName,
                parentPhone: this.queryData.parentPhone,
                className: this.queryData.className,
                status: this.queryData.status,
                areaId: this.queryData.areaId,
                classYear: this.queryData.classYear,
                classSeason: this.queryData.classSeason,
                orgId: this.baseuser.orgId
            })).then(res => {
                this.dataList = res.data.data.list;
                this.total = res.data.data.total;
            });
        },
        refresh () {
            this.queryData = {
                billCode: '',
                studentName: '',
                parentPhone: '',
                className: '',
                status: '',
                areaId: '',
                classYear: '',
                classSeason: ''
            };
            this.init();
            this.loadList();
        },
        showChargeDiscount: function () {
            this.chargeDiscountVisable = true;
            this.getDiscountType();
        },
        getOrderDetails: function () {
            this.orderDetails = {};
            this.class_dataList = [];
            this.charge_dataList = [];
            util.ajax.post('/busine/charge/detailBySql', util.toFormData({
                id: this.billId
            })).then(res => {
                if (res.data.code == 200 && res.data.data != '') {
                    this.orderDetails = res.data.data;
                    let ord = this.orderDetails;
                    let classSchedules = ord.classSchedules;
                    if (classSchedules) {
                        var text = '';
                        for (let i in classSchedules) {
                            let startTime = classSchedules[i].classStartTime;
                            let endTime = classSchedules[i].classEndTime;
                            if (startTime) {
                                startTime = startTime.substring(0, 2) + ':' + startTime.substring(2, 4);
                            }
                            if (endTime) {
                                endTime = endTime.substring(0, 2) + ':' + endTime.substring(2, 4);
                            }
                            text += util.convertNumToWeekOfDay(classSchedules[i].classType) + ' ' + startTime + '-' + endTime + ' ' + classSchedules[i].classRoomName;
                        }
                    }
                    let class_data = {
                        'class_code': ord.class_code,
                        'class_year': ord.class_year,
                        'class_season_name': ord.class_season_name,
                        'marjor_name': ord.marjor_name,
                        'teacher_name': ord.teacher_name,
                        'amt': ord.amt,
                        'classSchedules': text,
                        'class_name': ord.class_name
                    };
                    for (let i in ord.charges) {
                        let charge_data = {
                            'id': ord.charges[i].id,
                            'name': ord.charges[i].chargeName,
                            'amt': ord.charges[i].amt,
                            'realAmt': ord.charges[i].realAmt,
                            'discountedAmt': ord.charges[i].discountAmt,
                            'discountAmt': 0,
                            'discountRate': 100,
                            'chargeType': ord.charges[i].chargeType
                        };
                        this.charge_dataList.push(charge_data);
                    }
                    this.class_dataList.push(class_data);
                    if (ord.sex == 'MAN') {
                        this.orderDetails.sex = '男';
                    } else if (ord.sex == 'WOMAN') {
                        this.orderDetails.sex = '女';
                    }
                }
            });
        },
        countDiscount: function () {
            let discountRate = this.discountRate;
            if (discountRate != null && discountRate != '') {
                let charge_dataList = this.charge_dataList;
                for (let i in charge_dataList) {
                    let realAmt = charge_dataList[i].realAmt;
                    this.charge_dataList[i].discountRate = discountRate;
                    this.charge_dataList[i].discountAmt = parseFloat(realAmt) - (parseFloat(realAmt) * (parseFloat(discountRate) / 100));
                }
            }
        },
        doDiscount: function () {
            util.ajax.post('/busine/charge/doDiscount', util.toFormData({
                data: JSON.stringify(this.charge_dataList)
            })).then(res => {
                if (res.data.code == 200 && res.data.data != '') {
                    this.$Message.success(res.data.data);
                    this.getOrderDetails();
                }
            });
        },
        doPay: function () {
            if (this.payType == '') {
                this.$Message.warning('请选择支付方式');
                return;
            }
            var that = this;
            let ord = this.orderDetails;
            if (this.payType == 1) {
                this.$Modal.confirm({
                    title: '提示',
                    content: '确认应收金额:' + this.orderDetails.real_amt + '(元)?',
                    onOk: () => {
                        util.ajax.post('/busine/charge/doPay', util.toFormData({
                            id: that.orderDetails.id
                            // userId: that.baseuser.id
                        })).then(res => {
                            if (res.data.code == 200 && res.data.data != '') {
                                this.$Message.success(res.data.message);
                                this.chargeDetailVisable=false;
                                this.loadList();
                            } else {
                                this.$Message.error(res.data.message);
                            }
                        });
                    },
                    onCancel: () => {

                    }
                });
            } else if (this.payType == 14) {
                this.payNumVisible = true;
            } else if (this.payType == 2) { // 余额支付
                this.$Modal.confirm({
                    title: '提示',
                    content: '确认用余额支付金额:' + this.orderDetails.real_amt + '(元)?',
                    onOk: () => {
                        // 查询充值记录
                        util.ajax.post('/busine/bill/doPayByStudentBalance', util.toFormData({
                            studentId: that.orderDetails.studentId,
                            billId: that.orderDetails.id
                        })).then(res => {
                            if (res.data.code == 200 && res.data.data != '') {
                                this.$Message.success(res.data.message);
                                this.chargeDetailVisable=false;
                                this.loadList();
                            } else {
                                this.$Message.error(res.data.message);
                            }
                        });
                    },
                    onCancel: () => {}
                });
            }
        },
        payByWechat: function () {
            this.$Modal.confirm({
                title: '提示',
                content: '确认应收金额:' + this.orderDetails.real_amt + '(元)?',
                onOk: () => {
                    this.payNumVisible = true;
                    let payNum = this.payNum;
                    if (payNum) {
                        this.$Message.loading({
                            content: '支付中请稍后...',
                            duration: 0,
                            closable: true
                        });

                        util.ajax.post('/front/pay/unifypay', util.toFormData({
                            id: this.orderDetails.id,
                            auth_code: payNum
                        })).then(res => {
                            if (res.data.code == 1000) { // 免密支付成功
                                this.$Message.destroy();
                                this.$Notice.open({
                                    title: '支付消息',
                                    desc: '免密支付成功！',
                                    duration: 0
                                });
                                this.orderDetails.id = res.data.data.id;
                                this.cleanPayShit();
                                // this.queryWechatResult();
                            } else if (res.data.code == 1001 || res.data.code == 100) {
                                this.$Message.destroy();
                                this.$Notice.open({
                                    title: '支付消息',
                                    desc: res.data.message,
                                    duration: 0
                                });
                                this.cleanPayShit();
                            } else if (res.data.code == 1002) {
                                this.queryWechatResult();
                            }
                        });
                    }
                },
                onCancel: () => {

                }
            });
        },
        queryWechatResult: function () {
            util.ajax.post('/front/pay/querypay', util.toFormData({
                id: this.orderDetails.id
            })).then(res => {
                if (res.data.code == 1000) {
                    this.$Message.destroy();
                    this.$Notice.open({
                        title: '支付消息',
                        desc: res.data.data,
                        duration: 0
                    });
                } else if (res.data.code == 500 || res.data.code == 100) { // 业务逻辑错误
                    this.$Notice.open({
                        title: '支付消息',
                        desc: res.data.message,
                        duration: 0
                    });
                    this.cleanPayShit();
                } else {
                    this.queryWechatResult();
                }
            });
        },
        cleanPayShit: function () {
            this.payNumVisible = false;
            this.payNum = '';
            this.orderDetails.id = '';
        },
        cancelDiscount:function (id) {//取消打折
            util.ajax.post('/busine/charge/cancelDiscount', util.toFormData({
                id: id
            })).then(res => {
                if(res.data.code==200){
                    this.$Message.success(res.data.message);
                    this.getOrderDetails();
                }else{
                    this.$Message.error(res.data.message);
                }
            });
        }
    }
};
